package com.ytkj.digitalConstruction.socketio;

import java.util.LinkedHashMap;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.SocketIOClient;
import com.ytkj.digitalConstruction.redis.RedisHashService;
import com.ytkj.digitalConstruction.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 向客户端发送消息相关方法
 * 
 * @author momei
 *
 */
public class SendMessage {
	private final static Logger log = LoggerFactory.getLogger(SendMessage.class);

	@SuppressWarnings("unchecked")
	private static RedisHashService<ClientInfo> redisHashClientInfoService = SpringUtil.getBean(RedisHashService.class);
	@SuppressWarnings("unchecked")
	private static RedisHashService<LinkedHashMap<String,Object>> redisHashMapInfoService = SpringUtil.getBean(RedisHashService.class);
	
	/**
	 * 向客户端推送消息
	 * 
	 * @param clientId 客户端id
	 * @param data 需要发送的数据
	 */
	public static void sendMsg(String clientId,ChatObj data) {
		//获取到该客户端
		ClientInfo clientInfo = getClientInfo(clientId);
		if(clientInfo == null) {
			return;
		}
		UUID uuid = new UUID(clientInfo.getMostSignBits(),clientInfo.getLeastSignBits());
		SocketIOClient client = App.server.getClient(uuid);
		if(client != null) {
			client.sendEvent("chat", data);
		}else {
			log.error("socket-io client is null!");
		}
		
	}
	
	private static ClientInfo getClientInfo(String clientId) {
		String jsonStr = JSONObject.toJSONString(redisHashMapInfoService.get("client", clientId));
		return JSONObject.parseObject(jsonStr, ClientInfo.class);
	}

	/**
	 * 验证人员是否在线
	 *
	 * @param  clientId 客户端id
	 * @return Boolean
	 * @throws NullPointerException 空指针异常
	 */
	public static Boolean isLine(String clientId){
		if( redisHashClientInfoService.get("client", clientId) != null){
			return true;
		}else{
			return false;
		}


	}

}
